import { Component, OnInit, Injector } from '@angular/core';
import { ListBase } from 'app/modules/base/list-base';
import { Inject } from '@angular/compiler/src/core';
import { ClientMessageSendComponent } from '../client-message-send/client-message-send.component';
import { MySelection } from 'app/modules/base/selection';
import { ClientMessageTask } from '../../services/client-message.service';
import { Task, TaskService, TaskStatus } from 'app/modules/task/services/task.service';

@Component({
  selector: 'm-client-message-list',
  templateUrl: './client-message-list.component.html',
  styleUrls: ['./client-message-list.component.scss'],
})
export class ClientMessageListComponent extends ListBase implements OnInit {
  public taskStatus = TaskStatus;
  readonly root = '/message/client';
  JSON_stringify = JSON.stringify;
  readonly navs = [
    { title: '全部消息', url: this.root + '/all', index: 0 },
    { title: '已下发', url: this.root + '/success', index: 1 },
    { title: '已挂起', url: this.root + '/suspend', index: 2 },
    // { title: '下发中', url: this.root + '/sending' },
  ];
  private sub: any;
  type: string;
  constructor(private injector: Injector, private taskManager: TaskService) {
    super(injector);
  }
  result$ = this.getData('list');
  selection = new MySelection<Task>('sort_id');

  ngOnInit() {
    this.sub = this.route.params.subscribe((params) => {
      this.type = params['type'];
    });
  }

  create() {
    this.dialog.open(ClientMessageSendComponent);
  }

  canCancel(job: any) {
    if (
      job.status != this.taskStatus.Cancel &&
      job.status != this.taskStatus.Failed &&
      job.status != this.taskStatus.Finish
    ) {
      return true;
    }
    return false;
  }

  getSelectedIDList() {
    var ids = [];
    for (var task of this.selection.selected) {
      if (task.status == this.taskStatus.Finish) {
        this.toaster.warn('已完成的任务不能取消');
        return;
      } else {
        ids.push(task.jobs[0].id);
      }
    }
    return ids;
  }

  async cancel(...ids: number[]) {
    if ((await this.sweet.confirm('是否取消发送所选消息')).dismiss) {
      return;
    }
    if (!ids.length) {
      ids = this.getSelectedIDList();
    }
    for (let id of ids) {
      await this.taskManager.update({
        job_id: id,
        status: TaskStatus.Cancel,
      });
    }
    this.toaster.success('取消成功');
    this.reload();
  }
  async delete() {
    if ((await this.sweet.confirm('是否删除所选消息')).dismiss) {
      return;
    }
    await this.taskManager.delete(this.selection.keys());
    this.toaster.success('删除成功');
    this.reload();
  }
  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}
